package GUI;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;

import ctrLayer.ForestOwnerCtr;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

/**
 * ForestPanel class
 * @author Thomas
 */
public class ForestPanel extends JPanel {
	private JTable forestTable;
	private JScrollPane scrollPane;
	
	private ForestOwnerCtr forestOwnerCtr;
	private static ForestPanel instance;
	
	
	private ForestPanel() {
		forestOwnerCtr = ForestOwnerCtr.getInstance();
		setLayout(null);
		
		initilizeForestTable();
		initilizeComponemts();
	}
	
	public static ForestPanel getInstance() {
		if(instance == null) {
			instance = new ForestPanel();
		}
		return instance;
	}
	
	/**
	 * Method that creates the JTable
	 */
	private void initilizeForestTable() {
		String[][] data = forestOwnerCtr.forestListToArray();
		String[] columns = {"Forest nr", "Forest name", "Location", "Sqaurekilometres", "Natureoftrees", "Forest price", "Forest Owner", "Tree sort"};
	
			forestTable = new JTable(data, columns) {
			private static final long serialVersionUID = 1L;
			
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		
		forestTable.getTableHeader().setReorderingAllowed(false);
		forestTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		scrollPane = new JScrollPane(forestTable);
		forestTable.setFillsViewportHeight(true);
		forestTable.setAutoCreateRowSorter(true);
		scrollPane.setBounds(40,40,685,410);
		add(scrollPane);
		
		forestTable.setVisible(true);
	}
	
	private void initilizeComponemts() {
		JButton btnCreateForest = new JButton("Create forest");
		btnCreateForest.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				new CreateForestFrame();
			}
		});
		btnCreateForest.setBounds(600, 461, 125, 23);
		add(btnCreateForest);
		
		JButton btnDeleteForest = new JButton("Delete forest");
		btnDeleteForest.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				deleteForest();
			}
		});
		btnDeleteForest.setBounds(470, 461, 125, 23);
		add(btnDeleteForest);
	}
	
	public void updateTable() {
		forestTable.removeAll();
		this.remove(forestTable);
		scrollPane.removeAll();
		this.remove(scrollPane);
		initilizeForestTable();
		
	}
	
	/**
	 * Deletes the forest
	 */
	public void deleteForest() {
		int id = Integer.parseInt(forestTable.getValueAt(forestTable.getSelectedRow(), 0).toString());
		forestOwnerCtr.deleteForest(id);
		updateTable();
	}
}
